package mscs.data;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


public class FileDataStore {
	Class readClass;
	File file;
	public FileDataStore(Class readClass, File file) {
		this.readClass = readClass;
		this.file = file;
	}
	public List getClassArray() {
		ArrayList<Object> list = new ArrayList<Object>();
		try {
			BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
			String text = "";
			while((text = bufferedReader.readLine()) != null) {
				if (text.trim().equals(""))
					continue;
				Object instance = readClass.newInstance();
				String[] argsArray = text.split(",");
				Object result = null;
				Method[] methods = readClass.getMethods();
				ArrayList<String> methodList = new ArrayList<String>();
				int j = 0;
				for (int i = 0; i < methods.length; i++) {
					if (methods[i].getName().indexOf("set") == 0) {
						Class type = methods[i].getParameterTypes()[0];
						methods[i].invoke(instance, stringToType(type, argsArray[j++]));
					}
				}
				list.add(instance);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	public void write(List list) throws IOException {
		PrintWriter out = new PrintWriter(file);
		out.println("");
	}
	
	private String typeToString(Class type, Object data) {
		if (type.equals(Date.class)) {
			return dateToString((Date)data);
		} else {
			return data.toString();
		}
	}
	private Object stringToType(Class type, String data) throws ParseException {
		if (Date.class.equals(type)) {
			return stringTodate(data); 
		} else if (Integer.class.equals(type) || int.class.equals(type)) {
			return Integer.parseInt(data);
		} else if (Double.class.equals(type) || double.class.equals(type)) {
			return Double.parseDouble(data);
		} else if (Float.class.equals(type) || double.class.equals(type)) {
			return Float.parseFloat(data);
		} else if (String.class.equals(type)) {
			return data;
		} else if (Boolean.class.equals(data) || boolean.class.equals(type)) {
			return Boolean.parseBoolean(data);
		} else return null;
	}
	private String dateToString(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
		return sdf.format(date);
	}
	private Date stringTodate(String data) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
		return sdf.parse(data);
	}
}
